// Initialize your app
var myApp = new Framework7({
	swipeBackPage:false
});

// Export selectors engine
var $$ = Dom7;

// Add view
var mainView = myApp.addView('.view-main', {
    // Because we use fixed-through navbar we can enable dynamic navbar
    dynamicNavbar: true,
    domCache: true
});

var getValiCodeTimeItv,provinces,myImgData={},formData={};

$$('.myFields').on('keyup parste change', function () {
	checkNextStepBtn();
});


function checkNextStepBtn(){
	var phoneNumber = $$("#mobile").val();
	formData.phoneNo = phoneNumber;
	//if(phoneNumber.length==11 && phoneNumber.match(/^1[3|4|5|7|8][0-9]\d{4,8}$/)!=null){
	if(phoneNumber.length==11){
		var btnHtml = $$("#getValiCodeBtn").html().trim();
		if(btnHtml === '获取验证码'){
			$$("#getValiCodeBtn").removeClass("disabled");
		}
		var valiCode = $$("#valiCode").val();
		if(valiCode.length==6 && valiCode.match(/^\d{6}$/)!=null && $$("#agreeCkb")[0].checked){
			$$("#nextStepBtn").removeClass("disabled");
		}else{
			$$("#nextStepBtn").addClass("disabled");
		}
	}else{
		$$("#getValiCodeBtn").addClass("disabled");
		$$("#nextStepBtn").addClass("disabled");
	}
}

$$("#getValiCodeBtn").click(function(){
	$$.ajax({
    		type:'GET',
    		url:  '../user/verifiAction_customerRegisterSendValiCode.action',
    		data:{
    			terminalTypeId:$("#terminalTypeId").val(),
    			mobile:$$("#mobile").val(),
    			activationCode:$$("#activationCode").val()
			},
			success: function(data){
				
				var res = eval('('+data+')');
				if(res.code === '0'){
		    		$$("#getValiCodeBtn").addClass("disabled");
		    		$$("#getValiCodeBtn").html('60秒后重新获取');
		    		var time=60;
		    		getValiCodeTimeItv = setInterval(function(){
		    			time--;
		    			try{
			    			if(time<1){
			    				$$("#getValiCodeBtn").removeClass("disabled");
			    				$$("#getValiCodeBtn").html('获取验证码');
			    				clearInterval(getValiCodeTimeItv);
			    			}else{
			    				$$("#getValiCodeBtn").html(time+'秒后重新获取');
			    			}
		    			}catch(e){
		    				console.dir(e);
		    				clearInterval(getValiCodeTimeItv);
		    			}
		    		},1000);
		    	}else{
		    		myApp.alert(res.msg);
		    	}
			}
    	});
});


$$("#nextStepBtn").click(function(){
	$$.ajax({
		type:'GET',
		url:  '../user/verifiAction_customerRegisterValidatePhoneNo.action',
		data:{
			terminalTypeId:$("#terminalTypeId").val(),
			mobile:$$("#mobile").val(),
	     	valiCode:$$("#valiCode").val(),
	     	id:$$("#customerId").val()
		},
		success: function(data){
			var res = eval('('+data+')');
			if(res.code === '0'){
				mainView.router.load({pageName: 'pageResetPswd'});
				document.title = '设置登陆密码';
				clearInterval(getValiCodeTimeItv);
			}else if(res.code === '1'){
				$$("#muExistsFlag").val('Y');
				myApp.alert('您的手机号码已经在APP注册过，若需设置新的登录密码，请登录APP进行操作。','温馨提示',function(){
					findAccProvinceBack();
					mainView.router.load({pageName: 'pageCusBaseInfo'});
					document.title = '填写商户信息';
					clearInterval(getValiCodeTimeItv);
				});
			}else{
				myApp.alert( res.msg);
			}
		}
	});
});
$$(".myPswd").on('keyup parste change',checkResetPswdNextStepBtn);
function checkResetPswdNextStepBtn(){
	var pswd = $$("#password").val();
	var pswdConfirm = $$("#passwordConfirm").val();
	formData.password = pswd;
	if(pswd.match(/^[a-zA-Z0-9]{6,12}$/)!=null && pswdConfirm === pswd){
		$$("#resetPswdNextStepBtn").removeClass("disabled");
	}else{
		$$("#resetPswdNextStepBtn").addClass("disabled");
	}
}
$$("#resetPswdNextStepBtn").click(function(){
	$$.ajax({
		type:'GET',
		url:  '../user/userAction_customerRegisterResetPswd.action',
		data:{
			terminalTypeId:$("#terminalTypeId").val(),
	     	mobile:$$("#mobile").val(),
	     	password:$$("#password").val(),
	     	openId: $("#openId").val(),
	     	activationCode:$$("#activationCode").val()
		},
		success: function(data){
			var res = eval('('+data+')');
			if(res.code == '0'){
				
				$("#userId").val(res.userId);
				findAccProvinceBack();
				mainView.router.load({pageName: 'pageCusBaseInfo'});
				document.title = '填写商户信息';
			}else{
				myApp.alert( res.msg);
			}
		}
	});
});
function findAccProvinceBack(){
	var xhr = new XMLHttpRequest();
    xhr.open('GET', '../weixin/area_hsm.json', false);
    xhr.send(null);
    var areas = eval("(" + xhr.responseText + ")");
    areas = areas.items;
    provinces = new Array();
    for(var i=0;i<areas.length;i++){
    	var isNewProvince = true;
    	for(var j=0;j<provinces.length;j++){
    		if(provinces[j].code == areas[i].parent_code){
    			isNewProvince = false;
    			provinces[j].children.push({code:areas[i].code,name:areas[i].name});
    		}
    	}
    	if(isNewProvince){
    		provinces.push({code:areas[i].parent_code,name:areas[i].province,children:[{code:areas[i].code,name:areas[i].name}]});
    	}
    }
    var provinceOptions = '<option value="">请选择</option>';
    for(var k=0;k<provinces.length;k++){
    	provinceOptions += '<option value="'+provinces[k].code+'">'+provinces[k].name+'</option>';
    }
    myApp.smartSelectAddOption('#cusProvince', provinceOptions);
    myApp.smartSelectAddOption('#cusSettleProvince', provinceOptions);
}
//$$("#ss-cusbaseinfo-city").click(function(){
//	myApp.smartSelectOpen($$("#ss-cusbaseinfo-province"));
//});
myApp.onPageBeforeAnimation('pageCusBaseInfo',function(page){
	
});
$$("#cusProvince").on("change",function(){
	setCity('cusCity',$$("#cusProvince").val());
});
$$("#cusSettleProvince").on("change",function(){
	setCity('cusSettleCity',$$("#cusSettleProvince").val());
});
function setCity(target,parentCode){
	DWRUtil.removeAllOptions(target);
	var cityOptions = '<option value="" selected>请选择</option>';
	$$("#"+target).html('请选择');
	if(parentCode !== ''){
		for(var k=0;k<provinces.length;k++){
	    	if(parentCode === provinces[k].code){
	    		var citys=provinces[k].children;
	    		for(var i=0;i<citys.length;i++){
	    			cityOptions += '<option value="'+citys[i].code+'">'+citys[i].name+'</option>';
	    		}
	    	}
	    }
	}
	myApp.smartSelectAddOption('#'+target, cityOptions);
}
/*
$('input[type=file]').each(function(){
//$('#AAAAA').each(function(){
	var me = $(this);
	me.attr("accept","image/*");
	me.attr("capture","camera");
    me.on('change', function() {
    	$("#"+me.attr("id")+'_Show').val(me.val());
        var file = this.files[0];
        if(file){
        	//调用F7的Preloader会没有遮罩层，自己写一个，等Preloader完全显示了再处理图片
        	var _modalTemplateTempDiv = document.createElement('div');
        	var mdhtml = '<div class="modal modal-preloader"><div class="modal-inner"><div class="modal-title">正在处理图片，请稍候...</div><div class="modal-text"><div class="preloader"></div></div></div></div>';
        	_modalTemplateTempDiv.innerHTML = mdhtml;
        	var modal = $(_modalTemplateTempDiv).children();
        	$('body').append(modal[0]);
        	//Preloader opened，可以处理图片了
        	$$(modal).on("opened",function(){
        		var URL = window.URL || window.webkitURL;
                var blob = URL.createObjectURL(file);
                var img = new Image();
                var quality = 0.7;
                img.src = blob;
                img.onload = function() {
                 var that = this;
                    var w = that.width,h = that.height,scale = w / h;
                    h = w / scale;
                    //生成canvas
                    var canvas = document.createElement('canvas');
                    var ctx = canvas.getContext('2d');
                    $(canvas).attr({
                        width: w,
                        height: h
                    });
                    ctx.drawImage(that, 0, 0, w, h);
                    
                    //生成base64   兼容修复移动设备需要引入mobileBUGFix.js
                    var base64 = canvas.toDataURL('image/jpeg',  quality);
                    // 修复IOS
                    if (navigator.userAgent.match(/iphone/i)) {
                    	
                        var mpImg = new MegaPixImage(img);
                        mpImg.render(canvas, {
                            maxWidth: w,
                            maxHeight: h,
                            quality: quality
                        });
                        base64 = canvas.toDataURL('image/jpeg',quality);
                    }
                    // 修复android
                    if (navigator.userAgent.match(/Android/i)) {
                        var encoder = new JPEGEncoder();
                        base64 = encoder.encode(ctx.getImageData(0, 0, w, h), quality*100);
                    }
                    // 生成结果
                	
                    var result = {
                        base64: base64,
                        clearBase64: base64.substr(base64.indexOf(',') + 1),
                        target:me
                    };
                	
                    myImgData[me.attr('name')]=result.clearBase64;
                    //图片处理完成，关闭Preloader
                    myApp.hidePreloader();
                	
                };
        	});
        	//开启Preloader
        	myApp.openModal(modal);
        	
        }
    });
});
*/

document.querySelector('#cusIDFront').addEventListener('change', function () {
    var that = this;

    lrz(that.files[0], {
        width: 800
    })
        .then(function (rst) {
        	var base64 = rst.base64;
        	 myImgData.cusIDFront=base64.substr(base64.indexOf(',') + 1);
        	 //alert(myImgData.cusIDFront);
        	 $("#cusIDFront_Show").val("image.jpg");
            return rst;
        });
});

document.querySelector('#cusIDBack').addEventListener('change', function () {
    var that = this;

    lrz(that.files[0], {
        width: 800
    })
        .then(function (rst) {
        	var base64 = rst.base64;
        	 myImgData.cusIDBack=base64.substr(base64.indexOf(',') + 1);
        	// alert(myImgData.cusIDBack);
        	 $("#cusIDBack_Show").val("image.jpg");
            return rst;
        });
});

document.querySelector('#cusHoldIDFront').addEventListener('change', function () {
    var that = this;

    lrz(that.files[0], {
        width: 800
    })
        .then(function (rst) {
        	var base64 = rst.base64;
        	 myImgData.cusHoldIDFront=base64.substr(base64.indexOf(',') + 1);
        	 //alert(myImgData.cusHoldIDFront);
        	 $("#cusHoldIDFront_Show").val("image.jpg");
            return rst;
        });
});
//手持银行卡正面照
document.querySelector('#cusHoldCardFront').addEventListener('change', function () {
    var that = this;
    $("#cusHoldCardFront_Show").val("image.jpg");
    lrz(that.files[0], {
        width: 800
    })
        .then(function (rst) {
        	var base64 = rst.base64;
        	 myImgData.cusHoldCardFront=base64.substr(base64.indexOf(',') + 1);
        	 //alert(myImgData.cusHoldIDFront);
        	
            return rst;
        });
});




//开户许可证
document.querySelector('#cusBizLisence').addEventListener('change', function () {
    var that = this;
    $("#cusBizLisence_Show").val("image.jpg");
    lrz(that.files[0], {
        width: 800
    })
        .then(function (rst) {
        	var base64 = rst.base64;
        	 myImgData.cusBizLisence=base64.substr(base64.indexOf(',') + 1);
        	 //alert(myImgData.cusHoldIDFront);
        	
            return rst;
        });
});


/*

$('#cusIDFront').localResizeIMG({
		width: 800,
		quality: 1.0,
		success: function (result) {
	   myImgData.cusIDFront=result.clearBase64;
	   alert(result.clearBase64);
	  $("#cusIDFront_Show").val("\image.jpg");
   }
});

$('#cusIDBack').localResizeIMG({
	width: 800,
	quality: 1.0,
	success: function (result) {
    myImgData.cusIDBack=result.clearBase64;
    alert(result.clearBase64);
    $("#cusIDBack_Show").val("\image.jpg");
    }
});

$('#cusHoldIDFront').localResizeIMG({
	width: 800,
	quality: 1.0,
	success: function (result) {
		myImgData.cusHoldIDFront=result.clearBase64;
		alert(result.clearBase64);
		$("#cusHoldIDFront_Show").val("\image.jpg");
	}
});

//$('#cusHoldCardFront').localResizeIMG({
//	width: 800,
//	quality: 1.0,
//	success: function (result) {
//		myImgData.cusHoldCardFront=result.clearBase64;
//		$("#cusHoldCardFront_Show").val("\image.jpg");
//	}
//});
//
//$('#cusBizLisence').localResizeIMG({
//	width: 800,
//	quality: 1.0,
//	success: function (result) {
//		myImgData.cusBizLisence=result.clearBase64;
//		$("#cusBizLisence_Show").val("\image.jpg");
//	}
//});
*/
	
function alertObj(obj){
	var output = "";
	for(var i in obj){  
		var property=obj[i];  
		output+=i+" = "+property+"\n"; 
	}  
	alert(output);
} 
$(".myBaseInfo").bind('keyup parste change',function(){
	var cusName = $("#cusName").val().trim();
	var cusLgPson=$("#cusLgPson").val().trim();
	var cusIDNo=$("#cusIDNo").val().trim();
	var cusBusiness=$("#cusBusiness").val();
	var cusProvince=$("#cusProvince").val();
	var cusCity=$("#cusCity").val();
	var cusAddress = $("#cusAddress").val().trim();
	var cusIDFront=$("#cusIDFront").val();
	var cusIDBack=$("#cusIDBack").val();
	var cusHoldIDFront=$("#cusHoldIDFront").val();
	formData.cusName = cusName;
	formData.cusLgPson = cusLgPson;
	formData.cusIDNo = cusIDNo;
	formData.cusProvince = cusProvince;
	formData.cusCity = cusCity;
	formData.cusAddress = cusAddress;
	if(cusName.length>0&&cusLgPson.length>0&&cusIDNo.length>0&&cusProvince !=null &&cusProvince.length>0
			&&cusCity!=null&&cusCity.length>0&&cusAddress.length>0&& cusIDFront.length>0&&cusIDBack.length>0
			&&cusHoldIDFront.length>0&&idCardNoUtil.checkIdCardNo(cusIDNo)){
		
		$("#cusSettleAccName").val(cusName);
		$("#baseInfoNextStepBtn").removeClass("disabled");
	}else{
		$("#baseInfoNextStepBtn").addClass("disabled");
	}
});

$("#cusSettleAccBank,#cusSettleCity").change(function(){
	var bankId = $("#cusSettleAccBank").val();
	var bBankProvince = $("#cusSettleProvince").val();
	var bBankCity = $("#cusSettleCity").val();
	
//	if(bankCode != null && bankCode.length>0 && city != null && city.length>0){
//		customerRegisterService.findBankInfoByCityAndBankCode(city,bankCode,function(openBankList){
//			DWRUtil.removeAllOptions("cusSettleAccBankName");
//			myApp.smartSelectAddOption('#cusSettleAccBankName', '<option value="" selected>请选择</option>');
//			$$("#settle_openBankText").html('请选择');
//			if(openBankList != null && openBankList.length>0){
//				var options='';
//				for(var i=0;i<openBankList.length;i++){
//					options += '<option value="'+openBankList[i].alliedBankCode+','+openBankList[i].name+'">'+openBankList[i].name+'</option>';
//				}
//				myApp.smartSelectAddOption('#cusSettleAccBankName', options);
//			}
//		});
//	}
	
	//bankId  bBankProvince bBankCity
	if(bankId != null && bankId.length>0 && bBankCity != null && bBankCity.length>0){
		
		 $.ajax({
	          url:'../bank/bankAction_selectBranchesBankList.action',
	          type:'POST',
	          dataType : "json",
	          data:{
	        	  bankId : bankId,
	        	  bBankProvince : bBankProvince,
	        	  bBankCity : bBankCity
	          },
	          success:function(data){
	        	  DWRUtil.removeAllOptions("cusSettleAccBankName");
	        	  myApp.smartSelectAddOption('#cusSettleAccBankName', '<option value="" selected>请选择</option>');
	        	  $$("#settle_openBankText").html('请选择');
					if(data){
						 var options='';
						$.each(data,function(i,d){
							options += '<option value='+d.id+'>'+d.name+'</option>';
						});
						myApp.smartSelectAddOption('#cusSettleAccBankName', options);
					}
	          }
	 		 });
		
	}
});

$(".mySettleAccInfo").bind('keyup parste change',function (){
	var cusSettleAccNo = $("#cusSettleAccNo").val().trim();
	var cusSettleAccName=$("#cusSettleAccName").val().trim();
	var cusSettleAccBank=$("#cusSettleAccBank").val();
	var cusSettleProvince=$("#cusSettleProvince").val();
	var cusSettleCity=$("#cusSettleCity").val();
	var cusSettleAccBankName=$("#cusSettleAccBankName").val();
	var cusSettleAccImg=$("#cusHoldCardFront_Show").val();
	var cusBizLisenceImg=$("#cusBizLisence_Show").val();
	formData.cusSettleAccNo = cusSettleAccNo;
	formData.cusSettleAccName = cusSettleAccName;
	formData.cusSettleAccBank = cusSettleAccBank;
	formData.cusSettleProvince = cusSettleProvince;
	formData.cusSettleCity = cusSettleCity;
	formData.cusSettleAccBankName = cusSettleAccBankName;
	if(cusSettleAccNo.length>0&&cusSettleAccName.length>0 &&cusSettleAccBank.length>0
			&& cusSettleProvince.length>0 &&cusSettleCity!=null&&cusSettleCity.length>0
			&& cusSettleAccBankName != null &&cusSettleAccBankName.length>0
			&& (($$("#accTypeFlag").val() === 'INDIVIDUAL' && cusSettleAccImg.length>0) 
					|| ($$("#accTypeFlag").val() === 'OPEN' && cusBizLisenceImg.length>0))
					){
		$("#settleInfoSubmitBtn").removeClass("disabled");
	}else{
		$("#settleInfoSubmitBtn").addClass("disabled");
	}
});

$$("#settleInfoSubmitBtn").click(function(){
	//myApp.showPreloader('处理中...');
	//调用F7的Preloader会没有遮罩层，自己写一个，等Preloader完全显示了再处理图片
	var _modalTemplateTempDiv = document.createElement('div');
	var mdhtml = '<div class="modal modal-preloader"><div class="modal-inner"><div class="modal-title">请稍候...</div><div class="modal-text"><div class="preloader"></div></div></div></div>';
	_modalTemplateTempDiv.innerHTML = mdhtml;
	var modal = $$(_modalTemplateTempDiv).children();
	$$('body').append(modal[0]);
	//Preloader opened，可以处理图片了
	$$(modal).on("opened",function(){
		registerUser();
	});
	myApp.openModal(modal);
});

function registerUser(){

	var phoneNo = $$("#phoneNo").val();
	var customerNo = $$("#customerNo").val();
	var accTypeFlag = $$("#accTypeFlag").val();
	var userId = $$("#userId").val();
	var cusLgPson = $$("#cusLgPson").val();
	var cusIDNo = $$("#cusIDNo").val();
	var cusSettleAccNo = $("#cusSettleAccNo").val();
	myImgData['phoneNo']=phoneNo;
	myImgData['customerNo']=customerNo;
	myImgData['accTypeFlag'] = accTypeFlag;
	myImgData.userId = userId;
	myImgData['cusLgPson'] = cusLgPson;
	myImgData['cusIDNo'] = cusIDNo;
	myImgData['cusSettleAccNo'] = cusSettleAccNo;
	myImgData['terminalTypeId'] = $("#terminalTypeId").val();
	console.dir(myImgData);
	
	formData.id = $$("#customerId").val();
	formData.muExistsFlag = $$("#muExistsFlag").val();
	formData.accTypeFlag = $$("#accTypeFlag").val();
	formData.userId = $$("#userId").val();
	formData.terminalTypeId = $("#terminalTypeId").val();
	var openingBank = $("#cusSettleAccBank").find("option:selected").text();
	formData.openingBank = $$("#userId").val();
	formData.openingBank = openingBank;
	
	$.ajax({
		type:'POST',
		data: formData,
		url:  '../user/userAction_customerRegisterCreate.action',
		success: function(data){
			var res = eval('('+data+')');
			if(res.code == '0'){
				$$.ajax({
					type:'POST',
					data: myImgData,
					url:  '../user/userDPIAction_customerRegisterSaveCusImg.action',
					success: function(data){
						var res = eval('('+data+')');
						if(res.code == '0'){
							window.location.href="http://mu.1spay.com/mu/QR_download.html";
						}else{
							myApp.alert( res.msg);
						}
					},
					error: function(){
						myApp.hidePreloader();
						myApp.alert("图片上传失败！");
					}
				});
			}else{
				myApp.hidePreloader();
				myApp.alert(res.msg);
			}
		},
		error: function(){
			myApp.hidePreloader();
			myApp.alert("商户注册失败！");
		}
	});

}
$$('#tab1').on('show', function () {
    $$("#accTypeFlag").val('INDIVIDUAL');
    $$("#cusSettleAccName").val($$("#cusLgPson").val());
    $$("#cusSettleAccName").attr("readonly","readonly")
});
$$('#tab2').on('show', function () {
	$$("#accTypeFlag").val('OPEN');
	$$("#cusSettleAccName").removeAttr("readonly")
});

//function setTitle(title){
//	document.title = title;
//	var iiiiframe = $$('<iframe src="/favicon.ico"></iframe>');
//	iiiiframe.on('load',function() {
//		console.dir("111");
//        setTimeout(function() {
//        	iiiiframe.off('load').remove();
//        }, 0);
//    }).appendTo($$('body')[0]);
//}



//贷款基本信息下一步验证
$$("#loanNextBtn").click(function () {
	var job = $$("#job").val();
	var amount = $$("#amount").val();
	if( isNaN(amount) ){
		myApp.alert("请输入数字贷款额度！");
		$$("#amount").val("");
		$("#loanNextBtn").addClass("disabled");
		return;
	}
	if( amount<1 || amount>500 ){
		myApp.alert("贷款额度在1-500之间！");
		$$("#amount").val("");
		$("#loanNextBtn").addClass("disabled");
		return;
	}
	else{

		if( job == 1){
			mainView.router.load({pageName: 'pageGongxin'});
			$$("#jobType").html("");
			getjobType();
			$$("#jobYears").html("");
			getjobYears();
		}
		if( job == 2 ){
			mainView.router.load({pageName: 'pageQiye'});
			$$("#q_sellYears").html('');
			getsellYears();
			$$("#houseSum").html('');
			gethouseSum();

		}
		if( job == 3 ){
			mainView.router.load({pageName: 'pageWangluo'});
			$$("#platform").html('');
			getplatform();
			$$("#w_sellYears").html('');
			getsellYears();

		}
	}
});
//工薪族下一步验证
$$("#loanGongxinSubmitBtn").click(function(){
		var salary = $("#salary").val();
		if( isNaN(salary) ){
			myApp.alert("请输入数字月收入！");
			$("#salary").val('');
			$("#loanGongxinSubmitBtn").addClass("disabled");
			return;
		}else{
			$$.ajax({
				type:'POST',
				url:  '../user/userAction_customerLoans.action',
				data:{
					job:$("#job").val(),
					customerName:$("#customerName").val(),
					cusSettleProvince:$("#cusSettleProvinceLoan").val(),
					cusSettleCity:$("#cusSettleCity").val(),
					amount:$("#amount").val(),
					loanDate:$("#loanDate").val(),
					phone:$("#phoneNo").val(),
					jobType:$("#jobType").val(),
					jobYears:$("#jobYears").val(),
					salary:$("#salary").val(),
					userId:$("#loanUserId").val()
				},
				success: function(data){
					var res = eval('('+data+')');
					if(res.code == '0'){
						mainView.router.load({pageName: 'pageLoanSuccess'});
					}else{
						myApp.alert("贷款失败，请重新申请！");
					}
				}
			});
		}
});
//企业主下一步验证
$$("#loanQiyeSubmitBtn").click(function(){
	var yearSalary = $("#q_yearSalary").val();
	if ( isNaN(yearSalary) ){
		myApp.alert("请输入数字年销售额！")
		$("#q_yearSalary").val('');
		$("#loanQiyeSubmitBtn").addClass("disabled");
		return;
	}else {
		$$.ajax({
			type:'POST',
			url:  '../user/userAction_customerLoans.action',
			data:{
				job:$("#job").val(),
				customerName:$("#customerName").val(),
				cusSettleProvince:$("#cusSettleProvinceLoan").val(),
				cusSettleCity:$("#cusSettleCity").val(),
				amount:$("#amount").val(),
				loanDate:$("#loanDate").val(),
				phone:$("#phoneNo").val(),
				sellYears:$("#q_sellYears").val(),
				yearSalary:$("#q_yearSalary").val(),
				houseSum:$("#houseSum").val(),
				userId:$("#loanUserId").val()
			},
			success: function(data){
				var res = eval('('+data+')');
				if(res.code == '0'){
					mainView.router.load({pageName: 'pageLoanSuccess'});
				}else{
					myApp.alert("贷款失败，请重新申请！");
				}
			}
		});
	}
});
//网络商户下一步验证
$$("#loanWangluoSubmitBtn").click(function(){
	var yearSalary = $("#w_yearSalary").val();
	var sucSum = $("#sucSum").val();
	if ( isNaN(yearSalary) ){
		myApp.alert("请输入数字年销售额！");
		$("#w_yearSalary").val('');
		$("#loanWangluoSubmitBtn").addClass("disabled");
		return;

	}else if( isNaN(sucSum) ){
		myApp.alert("请输入数字月成交笔数！");
		$("#sucSum").val('');
		$("#loanWangluoSubmitBtn").addClass("disabled");
		return;
	}else{
		$$.ajax({
			type:'POST',
			url:  '../user/userAction_customerLoans.action',
			data:{
				job:$("#job").val(),
				customerName:$("#customerName").val(),
				cusSettleProvince:$("#cusSettleProvinceLoan").val(),
				cusSettleCity:$("#cusSettleCity").val(),
				amount:$("#amount").val(),
				loanDate:$("#loanDate").val(),
				phone:$("#phoneNo").val(),
				shopName:$("#shopName").val(),
				platform:$("#platform").val(),
				sellYears:$("#w_sellYears").val(),
				yearSalary:$("#w_yearSalary").val(),
				sucSum:$("#sucSum").val(),
				userId:$("#loanUserId").val()
			},
			success: function(data){
				var res = eval('('+data+')');
				if(res.code == '0'){
					mainView.router.load({pageName: 'pageLoanSuccess'});
				}else{
					myApp.alert("贷款失败，请重新申请！");
				}
			}
		});
	}
});
//贷款基本信息职业身份获取
function getJob(){
	var jobOptions ='<option value="">请选择</option>' +
		'<option value="1">工薪族</option>' +
		'<option value="2">企业主</option>' +
		'<option value="3">网络商户</option>';
	myApp.smartSelectAddOption('#job', jobOptions);
}
//贷款基本信息贷款期限获取
function getloanDate(){
	var loanDateOptions ='<option value="">请选择</option>' +
		'<option value="6个月以内">6个月以内</option>' +
		'<option value="6至12个月">6至12个月</option>' +
		'<option value="12个月以上">12个月以上</option>';
	myApp.smartSelectAddOption('#loanDate', loanDateOptions);
}
//工薪族职业类型获取
function getjobType(){
	var jobTypeOptions ='<option value="">请选择</option>' +
		'<option value="国家行政及事业单位">国家行政及事业单位</option>' +
		'<option value="国有企业">国有企业</option>' +
		'<option value="民营企业">民营企业</option>' +
		'<option value="外资企业">外资企业</option>' +
		'<option value="其他">其他</option>';
	myApp.smartSelectAddOption('#jobType', jobTypeOptions);
}
//工作年限获取
function getjobYears(){
	var jobYearsOptions ='<option value="">请选择</option>' +
		'<option value="6个月以内">6个月以内</option>' +
		'<option value="6个月至12个月">6个月至12个月</option>' +
		'<option value="12个月以上">12个月以上</option>';
	myApp.smartSelectAddOption('#jobYears', jobYearsOptions);
}
//经营年限获取
function getsellYears(){
	var sellYearsOptions ='<option value="">请选择</option>' +
		'<option value="1至2年">1至2年</option>' +
		'<option value="2至5年">2至5年</option>' +
		'<option value="5年以上">5年以上</option>';
	myApp.smartSelectAddOption('#q_sellYears', sellYearsOptions);
	myApp.smartSelectAddOption('#w_sellYears', sellYearsOptions);
}
//房产数量获取
function gethouseSum(){
	var houseSumOptions ='<option value="">请选择</option>' +
		'<option value="0套">0套</option>' +
		'<option value="1套">1套</option>' +
		'<option value="2套">2套</option>' +
		'<option value="2套以上">2套以上</option>';
	myApp.smartSelectAddOption('#houseSum', houseSumOptions);
}
//经营平台获取
function getplatform(){
	var platformOptions ='<option value="">请选择</option>' +
		'<option value="淘宝">淘宝</option>' +
		'<option value="天猫">天猫</option>' +
		'<option value="阿里巴巴">阿里巴巴</option>' +
		'<option value="京东">京东</option>' +
		'<option value="苏宁">苏宁</option>' +
		'<option value="1号店">1号店</option>' +
		'<option value="当当">当当</option>' +
		'<option value="亚马逊">亚马逊</option>' +
		'<option value="其他">其他</option>';
	myApp.smartSelectAddOption('#platform', platformOptions);
}
//点亮基本信息下一步按钮
$(".loanSettleAccInfo").bind('keyup parste change',function(){
	var job = $("#job").val();
	var customerName = $("#customerName").val().trim();
	var cusSettleProvince = $("#cusSettleProvinceLoan").val();
	var cusSettleCity = $("#cusSettleCity").val();
	var amount = $("#amount").val().trim();
	var loanDate = $("#loanDate").val();

	if ( job != '' && job != null && customerName != '' && customerName != null
		&& cusSettleProvince != '' && cusSettleProvince != null
		&& cusSettleCity != '' && cusSettleCity != null
		&& amount != '' && amount != null && loanDate != '' && loanDate != null
		){
		$("#loanNextBtn").removeClass("disabled");
	}else {
		$("#loanNextBtn").addClass("disabled");
	}
});
//点亮工薪族下一步按钮
$(".GxInfo").bind('keyup parse change',function(){
	var jobType = $("#jobType").val();
	var jobYears = $("#jobYears").val().trim();
	var salary = $("#salary").val().trim();
	if ( jobType != '' && jobType != null && jobYears != '' && jobYears != null && salary != '' && salary != null) {
		$("#loanGongxinSubmitBtn").removeClass("disabled");
	}
	else {
		$("#loanGongxinSubmitBtn").addClass("disabled");
	}
});
//点亮企业主下一步按钮
$(".QyInfo").bind('keyup parse change',function(){
	var q_sellYears = $("#q_sellYears").val();
	var q_yearSalary = $("#q_yearSalary").val().trim();
	var houseSum = $("#houseSum").val().trim();
	if ( q_sellYears != '' && q_sellYears != null && q_yearSalary != '' && q_yearSalary != null && houseSum != '' && houseSum != null) {
		$("#loanQiyeSubmitBtn").removeClass("disabled");
	}else {
		$("#loanQiyeSubmitBtn").addClass("disabled");
	}
});
//点亮网络商户下一步按钮
$(".WangluoInfo").bind('keyup parse change',function(){
	var shopName = $("#shopName").val();
	var platform = $("#platform").val().trim();
	var w_sellYears = $("#w_sellYears").val().trim();
	var w_yearSalary = $("#w_yearSalary").val().trim();
	var sucSum = $("#sucSum").val().trim();
	if ( shopName != '' && shopName != null && platform != '' && platform != null && w_sellYears != '' && w_sellYears != null
		&& w_yearSalary != '' && w_yearSalary != null && sucSum != '' && sucSum != null) {
		$("#loanWangluoSubmitBtn").removeClass("disabled");
	}else {
		$("#loanWangluoSubmitBtn").addClass("disabled");
	}
});
//点亮登陆按钮
function checkLoanNextStepBtn(){
	var phoneNo = $$("#phoneNo").val();
	var password = $$("#password").val();
	if( phoneNo != null && phoneNo != '' && password != null && password!= '' ){
		return true;
	}else{
		return false;
	}
}

//贷款登陆验证
$$("#loanNextStepBtn").click(function(){
	var terminalTypeId = $$("#terminalTypeId").val();
	console.log(terminalTypeId);
	$$.ajax({
		type:'POST',
		url:  '../user/customerLogin.action',
		data:{
			phoneNo:$$("#phoneNo").val(),
			password:$$("#password").val(),
			terminalTypeId:terminalTypeId
		},
		success: function(data){
			saveStorage();
			var res = eval('('+data+')');
			if(res.code == '0'){
				$("#loanUserId").val(res.userId);
				//alert(res.userId)
				var loanProCode = res.loanProvince;
                findAccProvinceBackLoan(loanProCode);
				var loanCiCode = res.loanCity;
				setCityLoan('cusSettleCity',loanProCode,loanCiCode);
				$("#loanDate").html('');
				getloanDate();
				$("#job").html('');
				getJob();
				$$("#customerName").val(res.loanUserName);
				mainView.router.load({pageName:'pageLoanBaseInfo'});
			}else{
				myApp.alert(res.msg);
				$$("#phoneNo").val('');
				$$("#password").val('');
			}
		},
		error:function(){
			myApp.alert( '登录失败');
			$$("#loginBtn").removeClass("disabled");
		}
	});
});
//验证手机号密码格式
function saveStorage(){
	var phoneNo = $("#phoneNo").val();
	localStorage.setItem("phoneNo",phoneNo);
	var password =  $("#password").val();
	localStorage.setItem("password",password);
}
//加载当前用户所在省
function findAccProvinceBackLoan(loanProCode){
    var loanProvinceCode = loanProCode;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', '../weixin/area_hsm.json', false);
    xhr.send(null);
    var areas = eval("(" + xhr.responseText + ")");
    areas = areas.items;
    provinces = new Array();
    for(var i=0;i<areas.length;i++){
        var isNewProvince = true;
        for(var j=0;j<provinces.length;j++){
            if(provinces[j].code == areas[i].parent_code){
                isNewProvince = false;
                provinces[j].children.push({code:areas[i].code,name:areas[i].name});
            }
        }
        if(isNewProvince){
            provinces.push({code:areas[i].parent_code,name:areas[i].province,children:[{code:areas[i].code,name:areas[i].name}]});
        }
    }
    var provinceOptions = '<option value="">请选择</option>';
    for(var k=0;k<provinces.length;k++){
        provinceOptions += '<option value="'+provinces[k].code+'">'+provinces[k].name+' </option>';
        if(loanProvinceCode == provinces[k].code){
            $("#loanProvince").html(provinces[k].name);
        }
    }
    myApp.smartSelectAddOption('#cusSettleProvinceLoan', provinceOptions);
}
//加载当前用户所在市
function setCityLoan(target,parentCode,loanCiCode){
	DWRUtil.removeAllOptions(target);
	var cityOptions = '<option value="" selected>请选择</option>';
	$$("#"+target).html('请选择');
	if(parentCode !== ''){
		for(var k=0;k<provinces.length;k++){
			if(parentCode == provinces[k].code){
				var citys=provinces[k].children;
				for(var i=0;i<citys.length;i++){
					cityOptions += '<option value="'+citys[i].code+'">'+citys[i].name+'</option>';
					if( loanCiCode == citys[i].code){
						$("#loanCity").html(citys[i].name);
					}
				}
			}
		}
	}
	myApp.smartSelectAddOption('#'+target, cityOptions);
}
// 改变省
$$("#cusSettleProvinceLoan").on("change",function(){
	$("#loanCity").html("请选择");
	$("#cusSettleCity").val('');
	setCity('cusSettleCity',$$("#cusSettleProvinceLoan").val());
});
$$('.myLoginFieldsBorder').on('keyup parste change', function () {
	if(checkLoanNextStepBtn()) {
		$("#loanNextStepBtn").removeClass("disabled");
	}else{
		$("#loanNextStepBtn").addClass("disabled");
	}
});
//默认显示登录过用户
$(function(){
	var storage = window.localStorage;
	var phoneNo = storage["phoneNo"];
	var password = storage["password"];
	if(phoneNo!="undefined" && password!="undefined"){
		$("#phoneNo").val(phoneNo);
		$("#password").val(password);
	}
	if(checkLoanNextStepBtn()){
		$("#loanNextStepBtn").removeClass("disabled");
	}else{
		$("#loanNextStepBtn").addClass("disabled");
	}
});
//忘记密码页中获取验证码
$$("#getLoanValiCodeBtn").click(function(){
	$$.ajax({
		type:'GET',
		url:  '../user/verifiAction_loanRegisterSendValiCode.action',
		data:{
			mobile:$$("#fp_phoneNo").val()
		},
		success: function(data){

			var res = eval('('+data+')');
			if(res.code === '0'){
				$$("#getLoanValiCodeBtn").addClass("disabled");
				$$("#getLoanValiCodeBtn").html('60秒后重新获取');
				var time=60;
				getValiCodeTimeItv = setInterval(function(){
					time--;
					try{
						if(time<1){
							$$("#getLoanValiCodeBtn").removeClass("disabled");
							$$("#getLoanValiCodeBtn").html('获取验证码');
							clearInterval(getValiCodeTimeItv);
						}else{
							$$("#getLoanValiCodeBtn").html(time+'秒后重新获取');
						}
					}catch(e){
						console.dir(e);
						clearInterval(getValiCodeTimeItv);
					}
				},1000);
			}else{
				myApp.alert(res.msg);
			}
		}
	});
});
//检查忘记密码页面基本要求，点亮相对应的按钮
$$('.myLoginFieldsBorder').on('keyup parste change', checkLoanForgetPswd1Fields);
function checkLoanForgetPswd1Fields(){
	var phoneNumber = $$("#fp_phoneNo").val();
	var imgValiCode = $$("#imgValiCode").val();
	if(phoneNumber.length==11 && phoneNumber.match(/^1[3|4|5|7|8][0-9]\d{4,8}$/)!=null){
		var btnHtml = $$("#getLoanValiCodeBtn").html().trim();
		if(btnHtml === '获取验证码'){
			$$("#getLoanValiCodeBtn").removeClass("disabled");
		}
		var valiCode = $$("#imgValiCode").val();
		if(valiCode.length==6 && valiCode.match(/^\d{6}$/)!=null){
			$$("#forgetPswdBtn").removeClass("disabled");
		}else{
			$$("#forgetPswdBtn").addClass("disabled");
		}
	}else{
		$$("#getLoanValiCodeBtn").addClass("disabled");
		$$("#forgetPswdBtn").addClass("disabled");
	}
}
//跳转重置密码
$("#forgetPswdBtn").click(function () {
	$$.ajax({
		type:'POST',
		url:'../user/verifiAction_loanRegisterValidatePhoneNo.action',
		data:{
			mobile:$("#fp_phoneNo").val(),
			valiCode:$("#imgValiCode").val()
		},
		success:function (data) {
			var res = eval('('+data+')');
			if( res.code == 0 ){
				mainView.router.load({pageName:'pageResetPswd'});
				clearInterval(getValiCodeTimeItv);
			}else if( res.code == 2 ){
				myApp.alert(res.msg);
				$("#imgValiCode").val('');
				clearInterval(getValiCodeTimeItv);
			}
		},
		error:function(){
			myApp.alert( '网络异常，请重试！');
			$("#fp_phoneNo").val('');
			$("#imgValiCode").val('');
		}
	});

});

//重置密码
$$(".loanPswd").on('keyup parste change',checkLoanResetPswdNextStepBtn);
function checkLoanResetPswdNextStepBtn(){
	var pswd = $("#loan_password").val();
	var pswd2 = $("#loan_password2").val();
	formData.password = pswd;
	if( pswd.match(/^[a-zA-Z0-9]{6,12}$/)!=null && pswd2 === pswd ){
		$$("#resetPswdBtn").removeClass("disabled");
	}else{
		$$("#resetPswdBtn").addClass("disabled");
	}
}
//提交新密码
$("#resetPswdBtn").click(function () {
	$$.ajax({
		type:'POST',
		url:'../user/userAction_customerResetPswd.action',
		data:{
			phoneNo:$$("#fp_phoneNo").val(),
			password:$$("#loan_password").val(),
			terminalTypeId:$$("#terminalTypeId").val(),
		},
		success: function(data){
			var res = eval('('+data+')');
			if(res.code == '9990' || res.code == '9991'){
				myApp.hidePreloader();
				myApp.alert(res.msg);
				$$("#password").val('');
				mainView.router.load({pageName:'pageCheckPhoneNo'});
			}
			if(res.code == '0'){
				myApp.alert("修改成功，请重新登录！");
				$("#password").val('');
				mainView.router.load({pageName:'pageCheckPhoneNo'});
			}else{

				myApp.alert( res.msg);
				mainView.router.load({pageName:'pageForgetPswd'});
			}
		},
		error:function(){
			myApp.alert('修改失败,请重试！');
			mainView.router.load({pageName:'pageForgetPswd'});
		}

	});
});



